//index.js
//获取应用实例
const app = getApp();
const imgBaseUrl = app.globalData.imgBaseUrl;
const imgPreUrl = app.globalData.imgPreUrl;

// console.log(app.globalData.imgBaseUrl);

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk, interval;
Page({
    data: {
        imgBaseUrl: imgBaseUrl,
        imgPreUrl: imgPreUrl,
        userLocation: true,
        redHidden: true,
        inArea: true,
        regionName: "运河区",
        regionList: [{
            id: 1,
            name: '运河区'
        }, {
            id: 2,
            name: '新华区'
        }, {
            id: 3,
            name: '高新区'
        }, {
            id: 4,
            name: '开发区'
        }],
        regionIndex: 0,
        scrollLeft: 0,
        activeIndex: 0,
        pullRefresh: false,
        indicatorDots: true,
        circular: true,
        autoplay: true,
        interval: 3000,
        duration: 1000,
        goodsList: [],
        specialGoods: [],
        specialID: 0,
        vipGoods: [],
        vipID: 0,
        hotGoods: [],
        hotID: 0,
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        countDownList: [],
        actEndTimeList: [],
        req1:false,
        cartNum:0,
        cateArr: []
    },

    onLoad: function() {

        // 实例化API核心类 旧
        qqmapsdk = new QQMapWX({
            key: 'KWSBZ-KQ5EW-6EKRD-OVGJF-6D27E-CHBHX'
        });
        var that = this;
        that.reqData1();

        //新
        // let endTimeList = [];
        // 将活动的结束时间参数提成一个单独的数组，方便操作
        // goodsList.forEach(o => {
        //     endTimeList.push(o.actEndTime)
        // })
        // this.setData({
        //     actEndTimeList: endTimeList
        // });
        // 执行倒计时函数
        // this.countDown();
        //获取数据
        this.getProjectLists();


    },
    onShow: function (){

        
        this.setData({
            isLogin: app.isLogin()
        });
        var that = this;
        if (!that.data.latitude || !that.data.userLocation) {
            that.getLocation();
        }
        if (that.data.isLogin) {
            that.getCartNum();
        }
        if (that.data.req1) {
            wx.showToast({
                title: '请登录',
                icon: 'none',
            });
            that.getEveryCar();
        }
    },
    timeFormat(param) { //小于10的格式化函数
        return param < 10 ? '0' + param : param;
    },
    countDown() { //倒计时函数
        // 获取当前时间，同时得到活动结束时间数组
        let newTime = new Date().getTime();
        let endTimeList = this.data.actEndTimeList;
        let countDownArr = [];

        // 对结束时间进行处理渲染到页面
        endTimeList.forEach(o => {
            let endTime = new Date(o).getTime();
            let obj = null;
            // 如果活动未结束，对时间进行处理
            if (endTime - newTime > 0) {
                let time = (endTime - newTime) / 1000;
                // 获取天、时、分、秒
                let day = parseInt(time / (60 * 60 * 24));
                let hou = parseInt(time % (60 * 60 * 24) / 3600);
                let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
                let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
                obj = {
                    day: this.timeFormat(day),
                    hou: this.timeFormat(hou),
                    min: this.timeFormat(min),
                    sec: this.timeFormat(sec)
                }
            } else { //活动已结束，全部设置为'00'
                obj = {
                    day: '00',
                    hou: '00',
                    min: '00',
                    sec: '00'
                }
            }
            countDownArr.push(obj);
        })
        // 渲染，然后每隔一秒执行一次倒计时函数
        this.setData({
            countDownList: countDownArr
        })
        setTimeout(this.countDown, 1000);
    },
    // PickerChange(e) {
    //     console.log(e)
    //     this.setData({
    //         index: e.detail.value
    //     })
    // },
    tabSelect(e) {
        this.setData({
            TabCur: e.currentTarget.dataset.id,
            scrollLeft: (e.currentTarget.dataset.id - 1) * 60
        })
    },
    tabClick: function(e) {
        var {
            index,
            id
        } = e.currentTarget.dataset;
    
        this.setData({
            activeId: id,
            activeIndex: index,
            scrollLeft: (index - 1) * 60
        })
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 0
        })
    },
    getUserInfo: function(e) {

        var that = this;
        var data = {};
        if(e.detail.errMsg == 'getUserInfo:ok'){

            // console.log('getUserInfo');
            that.login(e.detail.userInfo,e);
        }
    },
    getUserInfo1(e) {
        var that = this;
        var data = {};    
        if (e.detail.errMsg == "getUserInfo:ok") {
            that.login(e.detail.userInfo, e, 1);
        }
    },
    login: function(data, e, getmoney) {

        var that = this;
        wx.login({
            success: res => {
                data.code = res.code;
                // console.log(data);
                app.func.postReq('/text/index.php/home/login/adduser', data, function(res) {
                    if (res) {
                        that.setData({
                            user: res.users
                        })
                        wx.setStorageSync('hhh', res.users.id)
                        that.setData({
                            isLogin: 1
                        })
                        that.getEveryCar(1, e, getmoney);
                        if (getmoney) {
                            that.getNewMoney();
                        }
                    }
                })
            }
        })
    },
    reqData1: function() {

        var userid = wx.getStorageSync('hhh')
        if(!userid){

            wx.showToast({
                title: 'xssasd'
            });
        }
        var that = this;
        app.func.postReq('/text/index.php/home/product/plists', {}, function(res) {
            if (res.category) {
                var nodata = {};
                for (let i = 0, len = res.category.length; i < len; i++) {
                    var page = 'page' + res.category[i].id;

                    // console.log(page);
                    nodata['nodata' + res.category[i].id] = false;
                    that.setData({
                        [`page${res.category[i].id}`]: 2,
                        [`readMore${res.category[i].id}`]: true,
                    })
                }
                that.setData({
                    nodata: nodata
                });
            }
            if (res.user) {
                that.setData({
                    user: res.user
                })
                if (res.user.newp == 1) {
                    var redHidden = true;
                } else {
                    var redHidden = false;
                }
            } else {
                var redHidden = false;
            }
            var warning = [];
            var str = res.web.warning;
            var len = str.length / 42;
            for (var i = 0; i < len; i++) {
                var str1 = str.substring(i * 42, (i + 1) * 42);
                warning.push(str1);
            }

            console.log(res.pro);
            if(res.pro){

                that.dealCartGoods(res.pro);
            }
            that.dealCategory(res.category);
            that.setData({
                category: res.category,
                activeId: that.data.activeId ? that.data.activeId : res.category[0].id,
                // pro: res.pro ? res.pro : {},
                req1: true,
                newprice: parseFloat(res.web.newprice),
                redHidden: redHidden,
                warning: warning
            })
            that.setData({
                goodsList: res.product
            })
            // that.scrolltxt();
            var timer1 = setTimeout(function() {
                clearTimeout(timer1);
                wx.stopPullDownRefresh();
                that.setData({
                    pullRefresh: false
                })
            }, 1000)
        })
    },
    closeRed: function (){

        this.setData({
            redHidden: true
        });
    },
    getNewMoney: function (e){

        var that = this;
        if(!app.isLogin() || !that.data.user){

            wx.showToast({
                title: '请登录',
                icon: 'none',
                complete: () => {

                    // console.log('请登录');
                    that.getUserInfo(e,1);
                } 

            });
        }else if(that.data.user.newp == 1){

            // console.log('领过');
            wx.showToast({
                title: '您已领过此红包!',
                icon: 'none'
            });
            that.setData({
                redHidden: true
            });
        }else{

            app.func.postReq('/text/index.php/home/user/lqnew',{
                newprice: that.data.newprice
            },function (res){

                if(res == 1){

                    that.setData({
                        redHidden: true
                    });
                    wx.showToast({
                        title: '领取成功',
                        icon: 'none'
                    });
                }
            });

        }
    },
    getEveryCar: function(getCartNum, e, getmoney) {
        var that = this;
        app.func.postReq('/text/index.php/home/shopcar/everycar', {}, function(res) {
            
            that.dealCartGoods(res.pro);
            if (getCartNum == 1) {
                that.getCartNum(1, e, getmoney);
            }
        })
    },
    getCartNum: function(addcart, e, getmoney) {
        var that = this;
        app.func.postReq('/text/index.php/home/shopcar/cars', {}, function(res) {
            if (parseFloat(res) > 0) {
                wx.setTabBarBadge({
                    index: 2,
                    text: res.toString(),
                })
            }
            that.setData({
                cartNum: res
            })
            // console.log(getmoney);
            if (addcart && !getmoney) {
                that.addCart(e)
            }
        })
    },
    getLocation() {
        var that = this;
        wx.getLocation({
            success: function(res) {
                // console.group('getLocation');
                // console.log(res);
                // console.groupEnd();
                if (res.errMsg == "getLocation:ok") {
                    that.setData({
                        userLocation: true,
                        latitude: res.latitude,
                        longitude: res.longitude
                    })
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: res.latitude,
                            longitude: res.longitude
                        },
                        success: function(res) {

                            if (res.status == 0) {
                                console.log(res.result);
                                var lcity = res.result.address_component.city;
                                var larea = res.result.address_component.district;
                                var street_number = res.result.address_component.street_number;
                                var inArea; 
                                // console.log(lcity, larea);
                                if (lcity.indexOf("沧州") != -1) {
                                    //如果在沧州
                                    // if (larea.indexOf("运河") != -1 || larea.indexOf("新华") != -1) {
                                    //   inArea = true;
                                    // } else {
                                    //   inArea = false;
                                    // }
                                    if (larea.indexOf("沧县") == -1 &&
                                        larea.indexOf("青县") == -1 &&
                                        larea.indexOf("东光") == -1 &&
                                        larea.indexOf("海兴") == -1 &&
                                        larea.indexOf("盐山") == -1 &&
                                        larea.indexOf("肃宁") == -1 &&
                                        larea.indexOf("南皮") == -1 &&
                                        larea.indexOf("吴桥") == -1 &&
                                        larea.indexOf("献县") == -1 &&
                                        larea.indexOf("孟村") == -1 &&
                                        larea.indexOf("泊头") == -1 &&
                                        larea.indexOf("任丘") == -1 &&
                                        larea.indexOf("黄骅") == -1 &&
                                        larea.indexOf("河间") == -1 &&
                                        larea.indexOf("渤海") == -1) {
                                        inArea = true;
                                    } else {
                                        inArea = false;
                                        // 测试修改
                                        // inArea=true;
                                    }

                                } else {
                                    inArea = false;
                                }

                                // console.group('xxx');
                                // console.log(larea.substring(0, 1) + "...");
                                // console.groupEnd();

                                that.setData({
                                    inArea: inArea,
                                    // regionName: larea+street_number
                                    regionName: larea

                                })
                            }
                        },
                        fail: function(res) {
                            console.log('逆地址解析失败', res);
                        }
                    });
                }
            },
            fail: function(res) {
                console.log('获取经纬度失败', res);
                if (res.errMsg == "getLocation:fail auth deny") {
                    that.setData({
                        userLocation: false
                    })
                }
            }
        })
    },
    bindRegionChange(e) {
        var index = e.detail.value;
        var regionList = this.data.regionList;

        var name = regionList[index].name;
        var showName = name.substring(0, 3);
        if (!this.data.inArea) {
          this.reqData1();
        }


        // console.group('bindRegionChange');
        // console.log(index,regionList,name,showName);
        // console.groupEnd();

        this.setData({
            regionIndex: index,
            regionName: showName,
            inArea: true
        })
    },
    onPullDownRefresh: function() {
        this.setData({
            pullRefresh: true
        })
        this.reqData1();
    },
    bindGoodsDetail(e) {
        var id = e.currentTarget.dataset.id;
        if (id != 0) {
            wx.navigateTo({
                url: '../goodsdetail/goodsdetail?id=' + id,
            })
        }
    },
    groupbuy(e){

        //拼团暂未开放,敬请期待
        wx.showModal({
            title: '提示',
            content: '暂未开放,敬请期待'
        });
    },
    groupbuy1(e)
    {

        //3件八折暂未开放,敬请期待
        wx.showModal({
            title: '提示',
            content: '暂未开放,敬请期待'
        });
    },
    switchYuan(){

        wx.switchTab({
            url:'../vip/vip'
        });
    },
    switchchong(){
        wx.navigateTo({
            url:'../recharge/recharge'
        });
    },
    //获取专场接口
    getProjectLists()
    {

        var that = this;
        app.func.getReq('/text/index.php/home/Specialfield/specialfieldlist',{}, function(res) {

            if(res.data){

                res.data.forEach(o=>{

                    // console.log(o);
                    if(o.sf_name=='特色专区'){

                        that.setData({
                            specialID: o.sf_id,
                            // specialName: o.sf_name
                            specialName: 'special'
                        });
                        that.getSpecialGoods();
                    }else if(o.sf_name=='热销爆款'){

                        that.setData({
                            hotID: o.sf_id,
                            // hotName: o.sf_name
                            hotName: 'hot'

                        });
                        that.getHotGoods();
                    }else if(o.sf_name=='会员特价'){

                        that.setData({
                            vipID: o.sf_id,
                            // vipName: o.sf_name
                            vipName: 'vip'
                        });
                        that.getVipGoods();
                    }
                });
            }
        });

    },
    getSpecialGoods(){

        var that = this;
        app.func.getReq('/text/index.php/home/Specialfield/specialfieldinfo',{sfp_sfid:this.data.specialID}, function(res) {
            
            var tmp = new Array;

            if(res.data){

                res.data.forEach(o=>{

                    if(o.sfp_price){

                        o.finalprice = o.sfp_price;
                    }else if(o.user_price){

                        o.finalprice = o.user_price;
                    }else if(o.price){

                        o.finalprice = o.price;
                    }
                    tmp.push(o);
                });

                that.setData({

                    specialGoods : tmp
                });
            }
        });
    },
    getVipGoods(){

        var that = this;
        app.func.getReq('/text/index.php/home/Specialfield/specialfieldinfo',{sfp_sfid:this.data.vipID}, function(res) {
            
            var tmp = new Array;

            if(res.data){

                res.data.forEach(o=>{

                    if(o.sfp_price){

                        o.finalprice = o.sfp_price;
                    }else if(o.user_price){

                        o.finalprice = o.user_price;
                    }else if(o.price){

                        o.finalprice = o.price;
                    }
                    tmp.push(o);
                });

                that.setData({

                    vipGoods : tmp
                });
            }

        });
    },
    getHotGoods(){

        var that = this;
        app.func.getReq('/text/index.php/home/Specialfield/specialfieldinfo',{sfp_sfid:this.data.hotID}, function(res) {
            
            var tmp = new Array;

            if(res.data){

                res.data.forEach(o=>{

                    if(o.sfp_price){

                        o.finalprice = o.sfp_price;
                    }else if(o.user_price){

                        o.finalprice = o.user_price;
                    }else if(o.price){

                        o.finalprice = o.price;
                    }
                    tmp.push(o);
                });

                that.setData({

                    hotGoods : tmp
                });
            }
        });
    },
    addCart:function(e){
        const that=this;
        // var addClick=that.data.addClick;
        // if(!addClick){
        //   return;
        // }
        // that.setData({
        //   addClick:false
        // })
        // var timern=setTimeout(function(){
        //   clearTimeout(timern);
        //   that.setData({
        //     addClick:true
        //   })
        // },500);
        var id = e.currentTarget.dataset.id;
        var {id,num,cartnum,price,userprice,sfpprice,gtype}=e.currentTarget.dataset;

        // console.log( e.currentTarget.dataset );
        // console.log(num,cartnum);
        if(parseFloat(cartnum)>=parseFloat(num)){
          wx.showToast({
            title: '库存不足!',
            icon:'none'
          })
          return;
        }

        var cartNum=that.data.cartNum;
        cartNum+=1;

        wx.setTabBarBadge({
          index: 2,
          text: cartNum.toString(),
        })
        that.setData({          
            // pro:pro,
            cartNum: cartNum
        })

        gtype = gtype ? gtype : '';
        if(sfpprice){

            price = sfpprice;
        }else if(that.data.user.grade > 0 && userprice > 0){

            price = userprice;
        }

        app.func.postReq('/text/index.php/home/shopcar/addscar',{pid:id,num:1,goods_price:price,goods_type:gtype},function(res){
          
            if(res > 0){

                var pro = that.data.pro ? that.data.pro : {};
                if(gtype){

                    pro[id+gtype] = parseInt(res);
                }else{

                    pro[id] = parseInt(res);
                }
            }

            // console.group('addscar');
            // console.log(pro);
            // console.groupEnd(); 
            
            that.setData({          
                pro:pro
            });
        });
    }, 
    jianCart: function (e) {
        const that = this;
        var id = e.currentTarget.dataset.id;
        var gtype = e.currentTarget.dataset.gtype ? e.currentTarget.dataset.gtype : '';
        var pro = that.data.pro ? that.data.pro : {};
        var cartNum = that.data.cartNum;
        cartNum -= 1;
        if (parseInt(pro[id+gtype])==0){
          return;
        }
       
        that.setData({
          cartNum: cartNum
        })
        if(cartNum>0){
          wx.setTabBarBadge({
            index: 2,
            text: cartNum.toString(),
          });
        }else{
          wx.removeTabBarBadge({
            index:2
          });
        }
        app.func.postReq('/text/index.php/home/shopcar/minuescar',{pid:id,num:1,goods_type:gtype},function(res){
            //错误
            if(res < 0){

                cartNum++;
                that.setData({
                    cartNum: cartNum
                });
                wx.setTabBarBadge({
                    index: 2,
                    text: cartNum.toString(),
                  });

                return;
            }

            if(pro){

                if (parseInt(pro[id+gtype])==0){
                    return;
                }

                pro[id+gtype] = parseInt(res);
                that.setData({
                  pro: pro
                });
                // console.group('jian');
                //     console.log(pro);
                // console.groupEnd();
            }else{

                return;
            }
        })
    },
    dealCartGoods: function(goods){

        // console.log(goods);

        var data = {};
        goods.forEach(o=>{

            if(o.goods_type){

                data[o.goods_id+o.goods_type] = parseInt(o.num);
            }else{

                data[o.goods_id] = parseInt(o.num);
            }
        });

        // console.log(data);
        this.setData({
            pro: data
        });
    },
    dealCategory: function (Category){

        var cateArr = new Array();
        Category.forEach(o => {

            cateArr[o.id] = o.name
        });

        this.setData({
            cateArr : cateArr
        });
    },
    goSearch: function (){
        
        wx.navigateTo({

            url:'../search/search'

        });
    },
    GoGoodsDetail: function (e){

        var url = '../goodsdetail/goodsdetail?id='+ e.currentTarget.dataset.id;

        if(e.currentTarget.dataset.gtype){

            url += '&goods_type='+ e.currentTarget.dataset.gtype;

        }

        wx.navigateTo({

            url:url
        });
    },
    GoSpecialGoodsDetail: function (e){

        wx.navigateTo({

            url:'../Specialfield/specialfieldgoodsinfo?id='+e.currentTarget.dataset.id

        });
    }
    
})